package net.tv90.weatherserveradmin.controller;

import jakarta.servlet.http.HttpServletResponse;
import net.tv90.weatherserveradmin.model.dto.WeatherStationDataDTO;
import net.tv90.weatherserveradmin.service.WeatherStationService;
import net.tv90.weatherserveradmin.utils.Result;
import net.tv90.weatherserveradmin.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/api/weather")
public class WeatherStationController {

    @Autowired
    private WeatherStationService weatherStationService;

    // localhost:8080/api/weather/54511
    @GetMapping("/{stationIDs}")
    public Result getWeatherStationData(@PathVariable String stationIDs) {
        try {
            return Result.success(weatherStationService.getWeatherStationData(stationIDs, 7));
        } catch (RuntimeException e) {
            return Result.failed(e.getMessage());
        }
    }

    // localhost:8080/api/weather/54511/csv
    @GetMapping("/{stationIDs}/csv")
    public void getPast365DaysWeatherStationDataAsCSV(@PathVariable String stationIDs, HttpServletResponse response) {
        try {
            List<WeatherStationDataDTO> data = weatherStationService.getWeatherStationData(stationIDs, 7);
            response.setContentType("text/csv");
            response.setHeader("Content-Disposition", "attachment; filename=\"weather_station_data_" + stationIDs + "_" + TimeUtil.getNow() + ".csv\"");
            PrintWriter writer = response.getWriter();
            writer.println(WeatherStationService.ELEMENTS + ",weather_tomorrow");
            for (int i = 0; i < data.size(); i++) {
                WeatherStationDataDTO record = data.get(i);
                int weatherTomorrow = weatherStationService.ifRainTomorrow(record, data.subList(i + 1, data.size()));
                writer.println(
                        record.getStationId() + "," +
                                record.getYear() + "," +
                                record.getMonth() + "," +
                                record.getDay() + "," +
                                record.getHour() + "," +
                                record.getPrs() + "," +
                                record.getPrsSea() + "," +
                                record.getPrsMax() + "," +
                                record.getPrsMin() + "," +
                                record.getTem() + "," +
                                record.getTemMax() + "," +
                                record.getTemMin() + "," +
                                record.getRhu() + "," +
                                record.getRhuMin() + "," +
                                record.getVap() + "," +
                                record.getPre3h() + "," +
                                record.getWinDInstMax() + "," +
                                record.getWinSMax() + "," +
                                record.getWinDSMax() + "," +
                                record.getWinSAvg2mi() + "," +
                                record.getWinDAvg2mi() + "," +
                                record.getWepNow() + "," +
                                record.getWinSInstMax() + "," +
                                record.getVis() + "," +
                                record.getCloCov() + "," +
                                record.getCloCovLow() + "," +
                                record.getCloCovLm() + "," +
                                record.getDatetime() + "," +
                                weatherTomorrow
                );
            }
            writer.flush();
        } catch (RuntimeException | IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                response.getWriter().write("下载失败：" + e.getMessage());
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }


    // localhost:8080/api/weather/national
    @GetMapping("/national")
    public Result getNationalWeatherDataPrefab() {
        try {
            return Result.success(weatherStationService.getNationalWeatherDataPrefab());
        } catch (RuntimeException e) {
            return Result.failed(e.getMessage());
        }
    }

    // localhost:8080/api/weather/national/2024/11/3/20
    @GetMapping("/national/{yyyy}/{mm}/{dd}/{hh}")
    public Result getNationalWeatherDataPrefab(
            @PathVariable Integer yyyy,
            @PathVariable Integer mm,
            @PathVariable Integer dd,
            @PathVariable Integer hh) {
        try {
            if(hh == 0 || hh == 6 || hh == 12 || hh == 18) {
                return Result.success(weatherStationService.getNationalWeatherDataPrefab(LocalDateTime.of(yyyy, mm, dd, hh, 0)));
            } else {
                return Result.failed("非法的请求时间参数");
            }
        } catch (RuntimeException e) {
            return Result.failed(e.getMessage());
        }
    }

}
